package com.controller;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mypg.News;
import com.mypg.NewsHelper;
import com.mypg.Video;
import com.service.VideoService;
import org.apache.commons.fileupload.util.Streams;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.FrameGrabber;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RequestMapping("/video")
@Controller
public class VideoController {


    @Autowired
    VideoService videoService;

    @RequestMapping("/video_table_select.do")
    @ResponseBody
    public String doNews_table_select(String video_class,String video_class_sub,
                                      int page, int limit) throws ParseException, JsonProcessingException {
        int start_row=(page-1)*limit;
        int page_nums=limit;
        HashMap<String,Object> map=new HashMap<>();
        map.put("code",0);
        map.put("msg","");
        map.put("count",videoService.selectVideo_count_For_video_table_jsp(video_class,video_class_sub));
        List<Video> videoList=videoService.selectVideoFor_video_table_jsp(video_class,video_class_sub,start_row,page_nums);
        map.put("data", videoList);
        ObjectMapper mapper=new ObjectMapper();
        String map_json_str=mapper.writeValueAsString(map);
        return map_json_str;
    }

    @RequestMapping("/video_table_delete_one.do")
    @ResponseBody
    public void doVideo_table_delete_one(int video_id, HttpSession session){
        String path= (String) session.getAttribute("img_save_path");
        String path2=path;
        path+="/video_img/";
        path2+="/video_file/";
        Video video=videoService.selectVideoByVideo_id(video_id);
        File file1=new File(path+video.getVideo_img());
        file1.delete();
        File file2=new File(path2+video.getVideo_content());
        file2.delete();
        videoService.deleteVideoByVideo_id(video_id);
    }

    @RequestMapping("/video_table_delete_many.do")
    @ResponseBody
    public int doVideo_table_delete_many(String[] video_id_array,HttpSession session){
        video_id_array[0]=video_id_array[0].replace("[","");
        video_id_array[video_id_array.length-1]=video_id_array[video_id_array.length-1].replace("]","");
        String path= (String) session.getAttribute("img_save_path");
        String path2=path;
        path+="/video_img/";
        path2+="/video_file/";
        for(int i=0;i<video_id_array.length;i++){
            Video video=videoService.selectVideoByVideo_id(Integer.parseInt(video_id_array[i]));
            File file=new File(path+video.getVideo_img());
            file.delete();
            File file2=new File(path2+video.getVideo_content());
            file2.delete();
            videoService.deleteVideoByVideo_id(Integer.parseInt(video_id_array[i]));
        }
        return 0;
    }

    @RequestMapping("/video_table_add_with_file.do")
    @ResponseBody
    public void doVideo_table_add_with_file(String video_title, String video_class_sub,
                                                         @RequestParam(value="file_content",required = false) MultipartFile file_content,
                                                         @RequestParam(value="file_img",required = false) MultipartFile file_img,
                                                         HttpSession session) throws IOException {
        News news=new News();
        String content_to_upload="";
        String img_to_upload="";
        String video_length="0:00";

        if(file_content==null){
            content_to_upload="";
        }else{
            content_to_upload= UUID.randomUUID()+"_with_"+file_content.getOriginalFilename();
            String path= (String) session.getAttribute("img_save_path");
            path+="/video_file/";

            if(!file_content.isEmpty()){
                try {
                    File uploadFile=new File(path+content_to_upload);
                    Streams.copy(file_content.getInputStream(),new FileOutputStream(uploadFile.getAbsolutePath()),true);
                    video_length=getVideo_length(uploadFile);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        if(file_img==null){
            String path= (String) session.getAttribute("img_save_path");
            path+="/video_img/";
            img_to_upload=getVideo_img(file_content,path);
        }else{
            img_to_upload= UUID.randomUUID()+"_with_"+file_img.getOriginalFilename();
            String path= (String) session.getAttribute("img_save_path");
            path+="/video_img/";
            if(!file_img.isEmpty()){
                try {
                    File uploadFile=new File(path+img_to_upload);
                    Streams.copy(file_img.getInputStream(),new FileOutputStream(uploadFile.getAbsolutePath()),true);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        Video video=new Video();
        video.setVideo_title(video_title);
        video.setVideo_img(img_to_upload);
        video.setVideo_content(content_to_upload);
        video.setVideo_class(video_class_sub.substring(0,2));
        video.setVideo_class_sub(video_class_sub);
        video.setVideo_length(video_length);
        videoService.insertVideo(video);

    }

    public String getVideo_img(MultipartFile file_video,String picPath) throws IOException {
        File video=new File(picPath+"test.mp4");
        String res=UUID.randomUUID()+file_video.getOriginalFilename().replace(".","_")+".jpg";
        picPath+=res;
        Streams.copy(file_video.getInputStream(),new FileOutputStream(video.getAbsolutePath()),true);
        FFmpegFrameGrabber ff = new FFmpegFrameGrabber(video);
        try {
            ff.start();
            // 截取中间帧图片(具体依实际情况而定)
            int i = 0;
            int length = ff.getLengthInFrames();
            int middleFrame = length / 2;
            Frame frame = null;
            while (i < length) {
                frame = ff.grabFrame();
                if ((i > middleFrame) && (frame.image != null)) {
                    break;
                }
                i++;
            }
            // 截取的帧图片
            Java2DFrameConverter converter = new Java2DFrameConverter();
            BufferedImage srcImage = converter.getBufferedImage(frame);
            int srcImageWidth = srcImage.getWidth();
            int srcImageHeight = srcImage.getHeight();
            // 对截图进行等比例缩放(缩略图)
            int width = 480;
            int height = (int) (((double) width / srcImageWidth) * srcImageHeight);
            BufferedImage thumbnailImage = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
            thumbnailImage.getGraphics().drawImage(srcImage.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
            File picFile = new File(picPath);
            ImageIO.write(thumbnailImage, "jpg", picFile);
            ff.stop();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return res;
    }
    public String getVideo_length(File video){
        long duration = 0L;
        FFmpegFrameGrabber ff = new FFmpegFrameGrabber(video);
        try {
            ff.start();
            duration = ff.getLengthInTime() / (1000 * 1000);
            ff.stop();
        } catch (FrameGrabber.Exception e) {
            e.printStackTrace();
        }
        String res="";
        int mm= (int) Math.floor(duration/60);
        int ss= (int) (duration-(mm*60));
        res=mm+":"+ss;
        return res;
    }

    @RequestMapping("/video_table_edit.do")
    @ResponseBody
    public Map<String, Object> doVideo_table_edit(int video_id, String video_title,String video_class_sub,
                                                  String video_content,HttpSession session,String video_length,
                                                 @RequestParam(value="file_content",required = false) MultipartFile file_content) throws JsonProcessingException {
        String content_to_upload="";
        String video_length_to_upload="";
        String img_to_upload="";
        if(file_content==null){
            content_to_upload=video_content;
            video_length_to_upload=video_length;
        }else{
            content_to_upload= UUID.randomUUID()+"_with_"+file_content.getOriginalFilename();
            String path= (String) session.getAttribute("img_save_path");
            String path_start=path;
            path+="/video_file/";
            File file=new File(path+video_content);
            file.delete();
            path=path_start;
            path+="/video_img/";
            String video_img=videoService.selectVideoByVideo_id(video_id).getVideo_img();
            File file1=new File(path+video_img);
            file1.delete();
            if(!file_content.isEmpty()){
                try {

                    File uploadFile=new File(path_start+"/video_file/"+content_to_upload);
                    Streams.copy(file_content.getInputStream(),new FileOutputStream(uploadFile.getAbsolutePath()),true);
                    video_length_to_upload=getVideo_length(uploadFile);
                    img_to_upload=getVideo_img(file_content,path);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        Video video=new Video();
        video.setVideo_id(video_id);
        video.setVideo_title(video_title);
        video.setVideo_content(content_to_upload);
        video.setVideo_class(video_class_sub.substring(0,2));
        video.setVideo_class_sub(video_class_sub);
        video.setVideo_length(video_length_to_upload);
        videoService.updateVideoByVideo_id(video);
        videoService.updateVideo_imgByVideo_id(img_to_upload,video_id);
        HashMap<String,Object> map=new HashMap<>();
        map.put("str",content_to_upload);
        map.put("str_class",video_class_sub.substring(0,2));
        map.put("str_video_length",video_length_to_upload);
        map.put("str_video_img",img_to_upload);
        return map;
    }



    @RequestMapping("/video_table_edit_init.do")
    @ResponseBody
    public Video doVideo_table_edit_init(int video_id){
        return videoService.selectVideoByVideo_id(video_id);
    }

    @RequestMapping("/video_table_edit_upload_img.do")
    @ResponseBody
    public String doNews_table_edit_upload_img(@RequestParam(value="file",required = false) MultipartFile file_img,
                                               HttpSession session, int video_id) throws JsonProcessingException {
        HashMap<String, Object> map = new HashMap<>();
        if(session.getAttribute("flag_manager")!=null) {
            String img_to_upload = "";
            img_to_upload = UUID.randomUUID() + "_with_" + file_img.getOriginalFilename();
            String path = (String) session.getAttribute("img_save_path");
            path += "/video_img/";
            String video_img = videoService.selectVideoByVideo_id(video_id).getVideo_img();
            if (file_img != null) {
                if (!file_img.isEmpty()) {
                    File file = new File(path + video_img);
                    file.delete();
                    try {

                        File uploadFile = new File(path + img_to_upload);
                        Streams.copy(file_img.getInputStream(), new FileOutputStream(uploadFile.getAbsolutePath()), true);


//                    FileOutputStream fos = new FileOutputStream(path + img_to_upload);
//                    InputStream in = file_img.getInputStream();
//                    int a = 0;
//                    while ((a = in.read()) != -1) {
//                        fos.write(a);
//                    }
//                    in.close();
//                    fos.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    videoService.updateVideo_imgByVideo_id(img_to_upload, video_id);
                }

            }

            map.put("code", 0);
            map.put("msg", "");
            map.put("data", img_to_upload);
        }else{
            map.put("code", 0);
            map.put("msg", "");
            map.put("data", "fail");
        }
        return new ObjectMapper().writeValueAsString(map);
    }
}
